package com.hxs.email.task;

import cn.hutool.core.util.StrUtil;
import com.hxs.email.client.EduClient;
import com.hxs.email.pojo.entity.ScoreItem;
import com.hxs.email.pojo.entity.User;
import com.hxs.email.util.EmailSender;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class GradeQueryTask {


    @Autowired
    EmailSender emailSender;

    Map<User, Integer> userMap = new HashMap<>();

    @Scheduled(cron = "0 0 8-22 * * ?")
    public void gradeQuerySchedule() {

        int term = LocalDate.now().getMonthValue() > 8 ? 1 : 2;
        int currentYear = LocalDate.now().getYear();
        int year = term == 1 ? currentYear : currentYear - 1;
        term = term * term * 3;

        int finalTerm = term;

        if(userMap.isEmpty()){
            log.info("用户列表为空");
            return;
        }

        for(User user : userMap.keySet()){
            if(checkUser( user)){
                log.info("用户信息不完整 sid::{}", user.getSid());
                continue;
            }

            log.info("开始查询成绩 {}", user.getSid());
            Integer i = userMap.get(user);

            EduClient eduClient = new EduClient(null);
            eduClient.login(user.getSid(), user.getPassword());
            List<ScoreItem> studentScore = eduClient.getStudentScore(finalTerm, year);
            //有新成绩就推送
            if (studentScore.size() > i) {
                StringBuilder gradeInfo = new StringBuilder();
                for (ScoreItem scoreItem : studentScore) {
                    gradeInfo.append(scoreItem.getCourseName()).append(" ").append(scoreItem.getGrade()).append("\n");
                }
                emailSender.sendEmail(user.getEmail(), gradeInfo.toString());
                log.info("sid::{} 成绩发送成功", user.getSid());
                userMap.replace(user, studentScore.size());
            } else {
                userMap.replace(user, studentScore.size());
                log.info("sid::{} 暂无数据", user.getSid());
            }
        }
        userMap.forEach((user, i) -> {

        });

    }

    public void addUser(User user) {
        userMap.put(user, 0);
    }

    private boolean checkUser(User user){
        return (StrUtil.isEmpty(user.getSid()) || StrUtil.isEmpty(user.getPassword()) || StrUtil.isEmpty(user.getEmail()));
    }

}
